import comTitle from "@/views/com/com_title.vue";
import cropperModal from "@/components/cropper/index.vue";
import QuillEditor from "@/components/Editor/QuillEditor.vue";
import { fileBase64, toDecimal2 } from '@/utils/util'
import { addObj, goodstockfetchList, goodstockfetchListAll, shopgoodscategory, platformgoodscategory, goodstype, getTpyeId, merchantinfosupply, getObj, putObj, shopgoodsinfodetail } from '@/api/shop/goods.js'
import { upLoad } from '@/api/shop/upLoad.js'
import config from '@/config/appConfig'

export default {
    components: { comTitle, cropperModal, QuillEditor },
    data() {
        return {
            headers: {
                Authorization: "Bearer " + this.$store.getters.token,
            },
            labelWidth: "120px",
            disabled: false,
            ruleForm: {
                sptm: 1,
                saleScope: "00",
                detailList: [],
                saleState: '01'
            },
            soldOut: true,  //如初始库存为0，商品上架后为售罄状态
            rules: {
                goodsName: [
                    { required: true, message: "请输入商品名称，不超过30个字符", trigger: 'blur' },
                ],
                barCode: [
                    { required: true, message: "请输入商品条码", trigger: 'blur' },
                ],
                sptm: [
                    { required: true },
                ],
                sptm1: [
                    { required: true },
                ],
                sellingPrice: [{ required: true, message: "请输入销售价", trigger: 'blur' }],
                pid: [
                    { required: true, message: "请选择商品类目", trigger: 'change' },
                ],
                saleScope: [
                    { required: true, message: "请选择销售渠道", trigger: 'change' },
                ],
                stockNum: [
                    { required: true, message: "请输入库存数量", trigger: 'blur' }
                ],
                stockUnit: [
                    { required: true, message: "请选择库存单位", trigger: 'change' }
                ],
                convertUnit: [
                    { required: true, message: "请选择库存换算单位", trigger: 'change' }
                ],
                convertUnitNum: [{ required: true, message: "请输入库存换算数量", trigger: 'blur' }],
                typeId: [
                    { required: true, message: '请选择商品类型', trigger: 'change' },
                ],
                serviceDuration: [
                    { required: true, message: '请选择服务时长', trigger: 'change' },
                ],
                service: [
                    { required: true, message: '请选择服务时段', trigger: 'change' },
                ],
            },
            supplierMerchantIdList: [                //供应商名称

            ],
            stockUnitList: [], // 库存单位
            categoryIdList: [], //商品类目
            typeIdList: [], //商品类型
            typeIdAttribute: [],

            sptmPlaceholder: false,  //商品条码
            imageUrl: "",
            loading: false,  //上传
            optionsData: {
                title: "商品图片",     //弹框表头
                img: '',   //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 200, //默认生成截图框宽度
                autoCropHeight: 200, //默认生成截图框高度
                fixedBox: false, //固定截图框大小 不允许改变
                thumbnailName: "衣家生活"
            },
            number: 0,
            fileList: [],
            fileListUrl: [], //放大展示
            danwei: 1,
            imgUrlList: [],
            lgoodsSourceList: [
                {
                    label: '门店自建',
                    value: '00',
                },
                {
                    label: '平台推送',
                    value: '01',
                },
            ], //商品来源


            timer: null, //时长计算
            timeNum: 0,
            serviceDurationList: [  //服务时长
                // {
                //     label: "0",
                //     value: "00"
                // },
                {
                    label: "1",
                    value: "01"
                }, {
                    label: "2",
                    value: "02"
                }, {
                    label: "3",
                    value: "03"
                }, {
                    label: "4",
                    value: "04"
                }, {
                    label: "5",
                    value: "05"
                }, {
                    label: "6",
                    value: "06"
                }
            ],
            serviceTimesList: [],  //服务时段
        }
    },
    watch: {
        '$route'() {
            this.getList()
            this.getObjData() //编辑
        }
    },
    mounted() {
        this.getList()
        this.getObjData() //编辑
    },
    // 最后在beforeDestroy()生命周期内清除定时器：
    beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
    },
    updated() {
        if (this.timeNum == this.serviceTimesList.length) {
            this.clearTimer()
        }
    },
    methods: {
        getList() {
            // goodstockfetchList().then(val => {  //库存单位
            //     console.log(val)
            //     let data = val.data
            //     this.stockUnitList = data.records.map(item => {
            //         return {
            //             value: item.stockUnitId + '',
            //             label: item.stockUnitName
            //         }
            //     })
            // })
            goodstockfetchListAll().then(result => {
                console.log(result)
                let data = result.data
                this.stockUnitList = data.map(item => {
                    return {
                        value: item.stockUnitId + '',
                        label: item.stockUnitName
                    }
                })
            })



            shopgoodscategory({ businessType: this.$route.query.businessType, tenantId: this.$store.getters.userInfo.sysUser.tenantId, deptId: this.$store.getters.userInfo.sysUser.deptId }).then((val) => {
                let data = val.data
                this.categoryIdList = data.map((item) => {
                    return {
                        value: item.categoryId,
                        label: (item.categoryType == '00' ? '门店-' : '平台-') + item.categoryName,
                        // disabled: item.children.length ? false : true,
                        children: item.children.map((items) => {
                            return {
                                value: items.categoryId,
                                label: (items.categoryType == '00' ? '门店-' : '平台-') + items.categoryName,
                            }
                        }),
                    }
                })
                this.$forceUpdate()
            })
            goodstype().then(val => {  //商品类型
                let data = val.data
                this.typeIdList = data.records.map(item => {
                    return {
                        value: item.typeId,
                        label: item.typeName,
                        goodsAttributeName: item.goodsAttributeName
                    }
                })
            })
            merchantinfosupply().then(val => {  //供应商
                let data = val.data
                console.log(data)
                this.supplierMerchantIdList = data.records.map(item => {
                    return {
                        value: item.merchantId,
                        label: item.companyName,
                    }
                })
            })
        },
        getObjData() {
            if (this.$route.query.id) {
                shopgoodsinfodetail(this.$route.query.id).then(val => {
                    console.log(val)
                    this.ruleForm = val.data
                    if (this.ruleForm.barCode) {
                        this.ruleForm.sptm = 1
                        if (this.ruleForm.categoryId) {
                            let pid = []
                            pid.push(this.ruleForm.categoryId)
                            if (this.ruleForm.pid != '0') {  //pid 父级id
                                pid.unshift(this.ruleForm.pid)
                            }
                            this.ruleForm.pid = pid
                            console.log('pid', this.ruleForm.pid)
                            this.typeIdChange(this.ruleForm.typeId)  //商品属性
                        }
                        console.log('ruleForm', this.ruleForm)
                    }

                    let pic = []            //图片回显
                    if (this.ruleForm.goodsPic) {
                        if (this.ruleForm.goodsPic.indexOf(',') > -1) {
                            pic = this.ruleForm.goodsPic.split(',')
                            pic.forEach(item => {
                                this.fileList.push({ url: item, name: '商品图片' })
                                this.imgUrlList.push({ url: item, name: '商品图片' })
                            })
                        } else {
                            this.fileList.push({ url: this.ruleForm.goodsPic, name: '商品图片' })
                            this.imgUrlList.push({ url: this.ruleForm.goodsPic, name: '商品图片' })
                        }
                    }
                    if (this.$route.query.businessType == '04') { //服务时长
                        if (this.ruleForm.serviceDuration) {
                            this.serviceDurationChange(this.ruleForm.serviceDuration)
                            if (this.ruleForm.serviceTimes) {
                                this.ruleForm.service = this.ruleForm.serviceTimes.split(',')
                                this.ruleForm.service = [...this.ruleForm.service]
                            }

                        }
                    }

                    this.typeIdChange(this.ruleForm.typeId)
                    // this.goodsSourceChange(this.ruleForm.goodsSource)
                })
            }
        },
        goodsSourceChange(e) {
            this.categoryIdList = []
            if (e == '00') {
                shopgoodscategory({ businessType: this.$route.query.businessType, tenantId: this.$store.getters.userInfo.sysUser.tenantId, deptId: this.$store.getters.userInfo.sysUser.deptId }).then((val) => {
                    let data = val.data
                    this.categoryIdList = data.map((item) => {
                        return {
                            value: item.categoryId,
                            label: item.categoryName,
                            children: item.children.map((items) => {
                                return {
                                    value: items.categoryId,
                                    label: items.categoryName,
                                }
                            }),
                        }
                    })
                    this.$forceUpdate()
                })
            } else {
                platformgoodscategory({ businessType: this.$route.query.businessType }).then((val) => {
                    let data = val.data
                    this.categoryIdList = data.map((item) => {
                        return {
                            value: item.categoryId,
                            label: item.categoryName,
                            children: item.children.map((items) => {
                                return {
                                    value: items.categoryId,
                                    label: items.categoryName,
                                }
                            }),
                        }
                    })
                    this.$forceUpdate()
                })
            }
        },
        // popupVisibleChange(e) {
        //     if (e && !this.categoryIdList.length) {
        //         this.$message.warning('请选择商品来源')
        //     }
        // },
        typeIdChange(val) {  //商品类型关联出属性
            getTpyeId(val).then(val => {
                let data = val.data
                this.typeIdAttribute = data.map(item => {
                    return {
                        goodsAttributeName: item.goodsAttributeName,
                        goodsAttributeValues: item.goodsAttributeValue.split(','),
                        goodsAttributeId: item.goodsAttributeId,
                    }
                })
                this.typeIdAttribute = this.typeIdAttribute.map(item => {
                    return {
                        goodsAttributeName: item.goodsAttributeName,
                        goodsAttributeId: item.goodsAttributeId,
                        valueList: [],
                        goodsAttributeValues: item.goodsAttributeValues.map(items => {
                            return {
                                label: items,
                                value: items,
                            }
                        })
                    }
                })
                //编辑类型属性回显
                if (this.ruleForm.id) {

                    this.typeIdAttribute.forEach(item => {  //编辑类型属性回显
                        if (this.ruleForm.goodAttribute) {
                            this.ruleForm.goodAttribute.forEach(item1 => {
                                item1.goodAttributeValue.forEach(item2 => {
                                    if (item1.goodsAttributeId == item.goodsAttributeId) {
                                        item.valueList.push(item2.goodsAttributeValue)
                                    }
                                })
                            })
                        }

                    })

                }
                this.ruleForm.detailList = this.typeIdAttribute
                console.log(' this.ruleForm.detailList', this.ruleForm.detailList)
            })
        },
        changeHandler() { //商品属性
            this.ruleForm.detailList = this.typeIdAttribute.map(item => {
                return {
                    goodsAttributeId: item.goodsAttributeId,
                    valueList: item.valueList
                }
            })
        },
        sptmChange(e) {
            if (e == 0) {
                this.ruleForm = {
                    sptm: 0,
                    saleScope: '00',
                }
            }
        },
        serviceDurationChange(e) {  //服务时段
            let y = 6, z = 0, k = parseInt(e)   //y起始时间  z前面的字段值 k共有多少个可能
            this.timeNum = parseInt(16 / e)
            this.serviceTimesList = []
            this.ruleForm.service = []
            this.timer = setInterval(() => {
                z = y
                y += k
                this.serviceTimesList.push({ label: z + ':00 ' + '-' + y + ':00', value: z + ':00 ' + '-' + y + ':00' })
            }, 0)
        },
        clearTimer() {//清除定时器
            clearInterval(this.timer);
            this.timer = null;
        },

        submitSave() {   //提交并保存

            if (this.ruleForm.sptm == 0) {
                this.rules.sptm1[0].required = false;  //商品条码
            } else {
                this.rules.sptm1[0].required = true;
            }
            if (this.ruleForm.pid) {
                if (this.ruleForm.pid.length > 1) {  //商品类目
                    this.ruleForm.categoryId = this.ruleForm.pid[1]
                } else {
                    this.ruleForm.categoryId = this.ruleForm.pid[0]
                }
            }
            if (this.$route.query.businessType == '04') {  //服务时长
                let servicelist = [...this.ruleForm.service]
                this.ruleForm.serviceTimes = servicelist.join(',')
            }
            let urlList = [...this.imgUrlList]
            console.log(urlList)
            if (urlList.length) {  //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(config.url) > -1) {  //截取路径
                        item.url = item.url.replace(config.url, '')
                    }
                    console.log(item)
                    imgList.push(item.url)
                })
                this.ruleForm.goodsPic = imgList.join(',')
            }
            console.log(this.ruleForm.detailList)
            this.ruleForm.businessType = this.$route.query.businessType
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    // if (this.ruleForm.stockNum < this.ruleForm.convertUnitNum) {
                    //     this.$message.warning('库存数量必须大于等于库存换算数量')
                    //     return
                    // } else {

                    // }

                    if (this.$route.query.businessType == '02' || this.ruleForm.goodsPic) {
                        if (this.$route.query.id) {
                            // if (this.ruleForm.detailList.some(item => {
                            //     return item.valueList.length > 0
                            // })) {

                            // } else {
                            //     this.$message.warning('请选择商品类型关联出的属性')
                            // }
                            putObj(this.ruleForm).then(val => {
                                this.$message.success('修改成功')
                                this.quxiao('ruleForm')
                            })
                        } else {
                            // if (this.ruleForm.detailList.some(item => {
                            //     return item.valueList.length > 0
                            // })) {

                            // } else {
                            //     this.$message.warning('请选择商品类型关联出的属性')
                            // }
                            addObj(this.ruleForm).then(val => {
                                this.$message.success('添加成功')
                                this.quxiao('ruleForm')
                            })
                        }
                    } else {
                        this.$message.warning('请选择上传商品图片')
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // save() {   //保存
        //     console.log(this.ruleForm)
        //     if (this.ruleForm.sptm == 0) {
        //         this.rules.sptm1[0].required = false; //商品条码
        //     } else {
        //         this.rules.sptm1[0].required = true;
        //     }
        //     this.ruleForm.goodsPic = 'http://pic.netbian.com/uploads/allimg/200604/001849-15912011292fcb.jpg'
        //     console.log(this.ruleForm)
        //     this.$refs['ruleForm'].validate((valid) => {
        //         if (valid) {
        //             addObj(this.ruleForm).then(val > {

        //             })
        //         } else {
        //             console.log('error submit!!');
        //             return false;
        //         }
        //     });
        // },
        quxiao(ruleForm) {  //取消
            this.$router.go(-1)
            this.$refs[ruleForm].resetFields();
            this.ruleForm = {
                sptm: 1,
                saleScope: "00",
            }
        },

        handleChange(file) {  //上传触发
            // let { options } = this;
            // console.log(file)
            // fileBase64(file.file.originFileObj).then(result => {
            //     let target = Object.assign({}, options, {
            //         img: result.result,
            //         files: result.files
            //     })
            //     this.$refs['cropperModal'].edit(target);
            // })
            if (file.file.status === 'done') {
                console.log(file.file)
                this.imgUrlList.push({
                    uid: this.number++,
                    name: file.file.response.data.fileName,
                    status: 'done',
                    url: file.file.response.data.url
                });
                this.fileList.push({
                    uid: this.number++,
                    name: file.file.response.data.fileName,
                    status: 'done',
                    url: file.file.response.data.url
                })
            }
            console.log(file)
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('图片格式不支持！');
            }
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error('图片大小限制在10MB内!');
            }
            return isJpgOrPng && isLt10M;
        },
        setMaster(file) {  //设置主图
            console.log(this.fileList.indexOf(file))
            console.log(this.imgUrlList)
            let subFile = this.imgUrlList[this.fileList.indexOf(file)]  //找到提交的图片数组
            console.log(subFile)
            for (var i = 0; i < this.fileList.length; i++) {  //根据file 找到数组的位置
                if (this.fileList[i] === file) {
                    this.fileList.splice(i, 1);
                    this.imgUrlList.splice(i, 1);
                    break;
                }
            }
            this.imgUrlList.unshift(subFile);  //提交的图片
            this.fileList.unshift(file);  //回显的图片
            console.log(this.imgUrlList)
            console.log(this.fileList)
        },
        delUplod(file) {
            const index = this.fileList.indexOf(file)
            const newFileList = this.fileList.slice()
            newFileList.splice(index, 1)
            this.fileList = newFileList
            this.imgUrlList.splice(index, 1)
        },
        handleCropperSuccess(data) {  //图片裁切完成保存
            // fileBase64(data).then(result => {
            //     this.imageUrl = result.result
            //     this.fileListUrl.push(this.imageUrl)
            //     this.fileList.push({
            //         uid: this.number++,
            //         name: 'image.png',
            //         status: 'done',
            //         url: this.imageUrl
            //     })
            // })
            upLoad(data).then(res => {
                console.log(res)
                this.imgUrlList.push(res.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
        },
        toDecimalBlur(name) {  //保留两位小数
            // if (name === 'xsj') {
            //     this.ruleForm.sellingPrice = toDecimal2(this.ruleForm.sellingPrice)
            // } else if (name === 'cbj') {
            //     this.ruleForm.costPrice = toDecimal2(this.ruleForm.costPrice)
            // } else 
            if (name === 'xsj') {
                if (this.ruleForm.sellingPrice) {
                    this.ruleForm.sellingPrice = toDecimal2(this.ruleForm.sellingPrice) ? toDecimal2(this.ruleForm.sellingPrice) : 0
                    this.getGrossProfit()
                } else {
                    this.ruleForm.sellingPrice = 0
                    this.getGrossProfit()
                }

            } else if (name === 'cbj') {
                if (this.ruleForm.costPrice) {
                    this.ruleForm.costPrice = toDecimal2(this.ruleForm.costPrice) ? toDecimal2(this.ruleForm.costPrice) : 0
                    this.getGrossProfit()
                } else {
                    this.ruleForm.costPrice = 0
                }

            } else if (name === 'cxj') {
                if (this.ruleForm.promotePrice) {
                    this.ruleForm.promotePrice = toDecimal2(this.ruleForm.promotePrice) ? toDecimal2(this.ruleForm.promotePrice) : 0
                    this.getGrossProfit()
                } else {
                    this.ruleForm.promotePrice = 0
                    this.getGrossProfit()
                }

            } else
                if (name === 'kcsl') {

                    console.log('this.ruleForm.stockNum', this.ruleForm.stockNum)
                    this.ruleForm.stockNum = parseInt(this.ruleForm.stockNum)
                    // if(this.ruleForm.stockNum.indexOf('.')>-1){
                    //     console.log('this.ruleForm.stockNum111',this.ruleForm.stockNum)
                    //     this.ruleForm.stockNum = this.ruleForm.stockNum.split('.')[0]
                    // }
                    if (this.ruleForm.stockNum < 0) {
                        this.ruleForm.stockNum = 0
                    }
                }

        },

        getGrossProfit() {  //获取毛利
            this.ruleForm.grossProfit = ''
            if (this.ruleForm.promotePrice) {
                this.ruleForm.grossProfit = (this.ruleForm.promotePrice - this.ruleForm.costPrice).toFixed(2)
                this.getGrossProfitRate()
            } else {
                this.ruleForm.grossProfit = (this.ruleForm.sellingPrice - this.ruleForm.costPrice).toFixed(2)
                this.getGrossProfitRate()
            }

        },
        getGrossProfitRate() {//获取毛利率
            this.ruleForm.grossProfitRate = ''
            if (this.ruleForm.promotePrice) {
                this.ruleForm.grossProfitRate = (parseFloat(this.ruleForm.grossProfit) / parseFloat(this.ruleForm.promotePrice)).toFixed(4)
            } else {
                this.ruleForm.grossProfitRate = (parseFloat(this.ruleForm.grossProfit) / parseFloat(this.ruleForm.sellingPrice)).toFixed(4)
            }
            this.ruleForm.grossProfitRate = (this.ruleForm.grossProfitRate * 100).toFixed(2)
            console.log(this.ruleForm.grossProfitRate)
        },
        editorChange(quill, html, text) {  //富文本编辑器
            console.log(quill)
            console.log(html)
            console.log(text)
            this.ruleForm.goodsDetails = html
            console.log(this.ruleForm.goodsDetails)
        },
        addKchs() {    //库存换算新增
            this.ruleForm.kchs.push({});
        },
        editKchs(item) {  //库存换算删除
            let index = this.ruleForm.kchs.indexOf(item);
            if (index !== -1) {
                this.ruleForm.kchs.splice(index, 1);
            }
        },
        cxsjChange(e) {  //促销时间
            var timeList = [this.formDate(e[0]._d), this.formDate(e[1]._d)]
            this.ruleForm.startCxsj = timeList[0]
            this.ruleForm.endCxsj = timeList[1]
        },

    },
    filters: {
        businessType(val) {
            let obj = ''
            switch (val) {
                case '02':
                    obj = '商超'
                    break;
                case '03':
                    obj = '洗衣'
                    break;
                case '04':
                    obj = '家政'
                    break;
                case '05':
                    obj = '咖吧'
                    break;
            }
            return obj
        }

    },
} 